﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Xml;
using System.Xml.Serialization;

namespace Test
{
    public class RequestClass
    {
        /// <summary>
        /// Soap协议Post方法
        /// </summary>
        /// <param name="uri">WebService地址</param>
        /// <param name="str">传入Soap协议格式数据</param>
        /// <returns></returns>
        public static string SOAPRequest(Uri _uri, StringBuilder _str,string nameSpace,string nodeName)
        {
            string _returnstr = "";
            //发起请求
            WebRequest webRequest = WebRequest.Create(_uri);
            webRequest.ContentType = "text/xml; charset=utf-8";
            webRequest.Method = "POST";
            using (Stream requestStream = webRequest.GetRequestStream())
            {
                byte[] paramBytes = Encoding.UTF8.GetBytes(_str.ToString());
                requestStream.Write(paramBytes, 0, paramBytes.Length);  
            }
            //响应
            try
            {
                WebResponse webResponse = webRequest.GetResponse();
                using (StreamReader myStreamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
                {
                    _returnstr = myStreamReader.ReadToEnd();
                }
            }
            catch (WebException ex)
            {
                _returnstr = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
            }
            string req = HttpUtility.HtmlDecode(_returnstr);
            byte[] array = Encoding.UTF8.GetBytes(req);
            MemoryStream stream = new MemoryStream(array);

            //去掉非数据节点
            XmlTextReader Reader = new XmlTextReader(stream);
            Reader.MoveToContent();
            string result = HttpUtility.HtmlDecode(Reader.ReadInnerXml());

            XmlDocument xml = new XmlDocument();
            xml.LoadXml(result);
            XmlNode node = null;
            if (nameSpace == "")
            {
                node = xml.DocumentElement.SelectSingleNode($"//{nodeName}");
            }
            else
            {
                XmlNamespaceManager xmlNamespace = new XmlNamespaceManager(xml.NameTable);
                xmlNamespace.AddNamespace("ns", nameSpace);
                node = xml.DocumentElement.SelectSingleNode($"//ns:{nodeName}", xmlNamespace);
            }
            return node?.InnerXml;

            //return HttpUtility.HtmlDecode(_returnstr);
        }
        public static StringBuilder GetRequestStr(string xmlns, string name, Dictionary<string, string> parameter)
        {
            StringBuilder soap = new StringBuilder();
            soap.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            soap.Append($"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"  xmlns:soap=\"http://www.shaphar.com/SoapService\" xmlns:tem=\"{xmlns}\" >");
            soap.Append("<soapenv:Header/>");
            soap.Append("<soapenv:Body>");
            soap.Append($"<tem:{name}>");
            foreach (var item in parameter)
            {
                soap.Append($"<{item.Key}>");
                soap.Append($"{item.Value}");
                soap.Append($"</{item.Key}>");
            }
            soap.Append($"</tem:{name}>");
            soap.Append("</soapenv:Body>");
            soap.Append("</soapenv:Envelope>");
            return soap;
        }
        public static T XmlStrToObject<T>(string xmlStr) where T : class
        {
            if (string.IsNullOrEmpty(xmlStr)) return null;

            try
            {
                using (StringReader sr = new StringReader(xmlStr))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    return serializer.Deserialize(sr) as T;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }
    [XmlRoot(ElementName = "return")]//, Namespace = "http://tempuri.org/"
    public class Response
    {
        [XmlElement("result")]
        public result result { get; set; }
    }
    [XmlRoot("result")]
    public class result
    {
        [XmlElement("resultCode")]
        public string resultCode { get; set; }
        [XmlElement("id_card_value")]
        public string id_card_value { get; set; }
    }
}
